const express = require("express");
const mongoose = require("mongoose");

// 连接mongo 并使用udacity这个集合
const DB_URL = "mongodb://localhost:27017/udacity";
mongoose.connect(DB_URL);
mongoose.connection.on("connected", function() {
    console.log("mongo connect success");
});

// 类似于mysql表，mongo有文档，字段的概念
const User = mongoose.model("user", new mongoose.Schema({
    name: {type: String, require: true},
    age: {type: Number, require: true}
}));

// 新增
User.create({
    name: 'udacity',
    age: 18
}, function(err, doc) {
    if (!err) {
        console.log(doc);
    } else {
        console.log(err);
    }
})

// 删除
User.remove({age: 18}, function(err, doc) {
    console.log(doc);
});

// 更新
User.update({"name": "udacity"}, {"$set": {age: 22}}, function(err, doc) {
    console.log(doc);
});

const app = express();

app.get("/", function(req, res) {
    res.send("<h1>hello world1</h2>");
});

app.get("/data", function(req, res) {
    // 查
    User.find({}, function(err, doc) {
        res.json(doc);
    });
    // User.findOne(...)
    // res.send({name: "udacity", type: "IT"});
});

app.listen(9093, function() {
    console.log("Node app start at port 9093");
});